<template>
  <div class="classes" v-if="visiable">
    <a-card
      size="small"
      title="查询类别选择:"
      style="width: 300px; user-select: none"
      class="classes-card"
    >
      <div slot="extra" href="#">
        <a href="#" @click="onClose">
          <a-icon type="close" />
        </a>
      </div>

      <div v-show="isNoCless">暂无数据</div>
      <a-cascader
        :options="classesdata"
        placeholder="请选择类型"
        :load-data="loadDataClass"
        :field-names="{ label: 'title', value: 'id', children: 'children' }"
        style="width: 280px"
        @change="onChange"
      />
      <br />
      <AdvancedSearch ref="AdvancedSearch" @child-event="dealResult" />
    </a-card>
  </div>
</template>
<script>
import AdvancedSearch from "./AdvancedSearch";
import { getRootTreeData, getLeafTreeData } from "@/utils/buildTreeData"; //getLeafTreeData
import { getChildListBatch } from "@/utils/http/bootQuery";
import { jsonsort } from "@/utils/jsonsort";
export default {
  data() {
    return {
      visiable: false,
      classesdata: null,
      //为了方便处理，将每一个节点放置在数组中，选中的key循环匹配
      classeslist: [],
      prefix: "2020",
      selectedYear: null,
      yearsData: null,
      currentYearClasses: null,
      currentClass: null,
      isNoCless: false,
      isShowYear: true,
      selectedClass: "",
      //分类数据，Array，由一个个checkedlayers组成
      selectedClasses: [],
    };
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    SearchAreas() {
      return this.$store.state.config.SearchAreas[0];
    },
    SearchLayersNodes() {
      return this.$store.state.config.SearchLayersNodes;
    },
  },
  components: { AdvancedSearch },
  mounted() {
    this.onload();
  },

  methods: {
    dealResult(sql, datasetNames, dataUrl) {
      console.log("adcanceSearch", sql, datasetNames, dataUrl);
      var value = {};
      value.sql = sql;
      value.datasetNames = datasetNames;
      value.dataUrl = dataUrl;
      //将value传递给父组件
      this.$parent.searchByclass(value, 0, 10);
      this.visiable = false;
    },
    //动态加载类别，即查询下一节点的childern
    loadDataClass(treeNode) {
      treeNode = treeNode[treeNode.length - 1];

      let self = this;
      return new Promise((resolve) => {
        getChildListBatch({
          params: {
            parentIds: treeNode.id,
          },
        })
          .then((res) => {
            // 格式化图层树数据
            let data = res.data.result.records;
            treeNode.children = jsonsort(getLeafTreeData(data));

            // 更新图层树数据
            self.classesdata = [...self.classesdata];
            treeNode.children.map((item) => {
              self.classeslist.push(item);
              // console.log("555", self.classeslist);
            });

            resolve(true);
          })
          .catch((err) => {
            console.error(err);
          });
      });
    },
    //级联选中事件，调用了选择事件，
    onChange(treenode) {
      if (!treenode) {
        this.$refs.AdvancedSearch.onClose();
      }
      let tagitem = this.classeslist.filter(
        (item) => item.id == treenode[treenode.length - 1]
      )[0];
      if (!tagitem) {
        return;
      }
      if (
        tagitem.hasChild != null &&
        tagitem.hasChild == "0" &&
        tagitem.dadaUrl != null
      ) {
        if (tagitem.dadaUrl == "") {
          this.$message.warning("数据服务为空,不可选");
          return;
        }
        //为了方便处理，将每一个节点放置在数组中，选中的key循环匹配，前缀为第一个节点
        this.prefix = this.classeslist.filter(
          (item) => item.id == treenode[0]
        )[0].title;
        console.log("tagitem", tagitem);

        this.$refs.AdvancedSearch.tagitem = tagitem;
        this.$refs.AdvancedSearch.selectedField = "选择查询字段";
        this.$refs.AdvancedSearch.getSearchField();
      }
    },
    async searchTypeChange(selectedId) {
      if (!selectedId) {
        this.$emit("selectedClass", null);
        this.selectedClasses = [];
        return;
      }
      this.currentClass = selectedId;
      let tempyearchild = await this.getChild(selectedId);
      if (!tempyearchild.length) {
        this.isNoCless = true;
        this.currentYearClasses = [];
        (this.yearsData = []), (this.prefix = null), (this.isShowYear = false);
      } else if (tempyearchild[0].hasChild === "1") {
        this.isNoCless = false;
        this.isShowYear = true;
        this.yearsData = tempyearchild;
        this.prefix = this.yearsData[0].title;
        this.currentYearClasses = await this.getChild(this.yearsData[0].id);
      } else {
        this.isNoCless = false;
        this.isShowYear = false;
        this.prefix = null;
        this.currentYearClasses = tempyearchild;
      }
    },

    //获取树的根节点
    async onload() {
      this.classesdata = JSON.parse(
        JSON.stringify(await getRootTreeData(this.SearchLayersNodes))
      );
      this.classesdata.map(
        (item) => ((item.isLeaf = false), this.classeslist.push(item))
      );
      console.log(this.classesdata);
      this.currentClass = this.classesdata[0].id;
      await this.searchTypeChange(this.classesdata[0].id);
      this.selectedYear = this.yearsData[0].id;
      this.prefix = this.yearsData[0].title;
    },
    //获取子节点
    getChild: function (parentId) {
      return new Promise((resolve) => {
        getChildListBatch({
          params: {
            parentIds: parentId,
          },
        })
          .then((res) => {
            let data = res.data.result.records;
            resolve(data);
          })
          .catch((err) => {
            console.error(err);
          });
      });
    },
    onClose() {
      this.visiable = false;
      this.$refs.AdvancedSearch.onClose();
      this.$parent.isshowClasses = !this.$parent.isshowClasses;
      console.log(this.$parent);
    },
    dealresult(result) {
      if (!result) {
        this.$message.destroy();
        this.$message.error("区划服务错误，请联系管理员");

        return;
      } else if (result.totalCount < 1) {
        this.$message.destroy();
        this.$message.warning("暂无数据");

        return;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.classes-card {
  white-space: normal;
  //text-overflow: ellipsis;
  // white-space: nowrap;
  /deep/ .ant-card-head {
    min-height: 20px;
    margin-bottom: -1px;
    padding: 0 10px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
    background: transparent;
    border-bottom: 1px solid #e8e8e8;
    border-radius: 2px 2px 0 0;
    zoom: 1;
    border: none;
    .ant-card-head-wrapper > .ant-card-extra {
      padding: 0px 0;
      font-size: 12px;
    }
  }
}
.classes-card:hover {
  //overflow: auto;
  white-space: normal;
}
.search-type-class {
  .ant-select-sm .ant-select-selection--single {
    min-width: 60px;
  }
}
</style>
